from django.contrib import admin
from celery_tasks.html.tasks import generate_static_sku_detail_html
from celery_tasks.html.tasks import generate_static_list_search_html
from . import models


class GoodsCategoryAdmin(admin.ModelAdmin):
    """商品分类站点管理类"""

    def save_model(self, request, obj, form, change):
        """钩子方法，在运营站点中编辑/添加数据时，会自动执行代码"""
        # 保存操作
        obj.save()
        # 保存操作后，执行异步任务
        generate_static_list_search_html.delay()

    def delete_model(self, request, obj):
        """钩子方法，在删除数据的时候自动执行"""
        obj.delete()
        generate_static_list_search_html.delay()


class GoodsChannelAdmin(admin.ModelAdmin):
    """商品频道站点管理类"""

    def save_model(self, request, obj, form, change):
        """钩子方法，在运营站点中编辑/添加数据时，会自动执行代码"""
        # 保存操作
        obj.save()
        # 保存操作后，执行异步任务
        generate_static_list_search_html.delay()

    def delete_model(self, request, obj):
        """钩子方法，在删除数据的时候自动执行"""
        obj.delete()
        generate_static_list_search_html.delay()


class SKUAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        generate_static_sku_detail_html.delay(obj.id)


class SKUSpecificationAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        generate_static_sku_detail_html.delay()

    def delete_model(self, request, obj):
        sku_id = obj.sku.id
        obj.delete()
        generate_static_sku_detail_html.delay(sku_id)


class SKUImageAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        generate_static_sku_detail_html.delay(obj.sku.id)
        # 设置ＳＫＵ默认图片
        sku = obj.sku
        if not sku.default_image_url:
            sku.default_image_url = obj.image.url
            sku.save()

    def delete_model(self, request, obj):
        sku_id = obj.sku.id
        obj.delete()
        generate_static_sku_detail_html.delay(sku_id)


# 注册模型类
admin.site.register(models.GoodsCategory, GoodsCategoryAdmin)
admin.site.register(models.GoodsChannel, GoodsChannelAdmin)
admin.site.register(models.Goods)
admin.site.register(models.Brand)
admin.site.register(models.GoodsSpecification)
admin.site.register(models.SpecificationOption)
admin.site.register(models.SKU, SKUAdmin)
admin.site.register(models.SKUSpecification, SKUSpecificationAdmin)
admin.site.register(models.SKUImage, SKUImageAdmin)
